var express = require('express');
var router = express.Router();
const { User, bookinfo, Laboratory, Equipment } = require('../../models')
const { success, failure } = require('../../util/requestResult')
const { NotFoundError, BadRequestError, UnauthorizedError, AlreadyExistsError, SequelizeValidateError } = require('../../util/errors')
// 查询条件限制
const condition = {
    include: [
        {
            model: bookinfo,
            as: 'bookinfos',
            attributes: ['id', 'startTime', 'endTime'],
            include: [
                {
                    model: Laboratory,
                    as: 'Laboratory',
                    attributes: ['id', 'laboratoryName']
                },
                {
                    model: Equipment,
                    as: 'Equipment',
                    attributes: ['id', 'equipmentName']
                },
            ]
        },
    ]
}
// 查询所有用户
router.get('/', async function (req, res, next) {
    try {
        let users = await User.findAll(condition)
        success(res, '查询所有用户成功', users)
    } catch (error) {
        failure(res, error)
    }

})

// 按id查找用户
router.get('/:id', async function (req, res, next) {
    try {
        let users = await getuser(req, true)
        success(res, `查询id为${req.params.id}的用户成功`, users)
    } catch (error) {
        failure(res, error)
    }
})


// 按account查找用户
router.get('/account/:account', async function (req, res, next) {
    try {
        let { account } = req.params
        let user = await User.findOne({ where: { account } })
        success(res, `查询学号为${account}的用户成功`, user)
    } catch (error) {
        failure(res, error)
    }
})


// 新增用户
router.post('/', async function (req, res, next) {
    try {
        let userInfo = filterBody(req)
        let user = await User.findOne({ where: { account: userInfo.account } })
        if (user)
            throw new AlreadyExistsError("此账号已存在");
        let createduser = await User.create(userInfo)
        success(res, '创建用户成功', createduser, 201)
    } catch (error) {
        failure(res, error)
    }

})

// 更新用户
router.put('/:id', async function (req, res, next) {
    try {
        let userInfo = filterBody(req)
        let user = await getuser(req)
        await user.update(userInfo)
        success(res, `更新id为${req.params.id}用户成功`, user)
    } catch (error) {
        failure(res, error)
    }

})


// 删除用户
router.delete('/:id', async function (req, res, next) {
    try {
        let user = await getuser(req)
        await user.destroy()
        success(res, `删除id为${req.params.id}用户成功`)
    } catch (error) {
        failure(res, error)
    }
})


function filterBody(req) {
    let { account, name, password, role } = req.body
    return { account, name, password, role }
}


async function getuser(req, isCondition) {
    const { id } = req.params
    let users = await User.findByPk(id, isCondition ? condition : {})
    if (!users)
        throw new NotFoundError(`未查询到id为${id}的用户`)
    return users
}

module.exports = router